// src/views/Risk/Risk.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Table, Card, Spin, message, Badge, Button, Modal, Typography } from 'antd';
import { InfoCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { $getAssetRiskDetail } from '../../api/riskApi';
import { $getUserAssets } from '../../api/userAssetApi';
import './Risk.scss';

const { Text } = Typography;

/** 从 localStorage 获取用户 ID */
const getUserId = () => {
  const userInfo = localStorage.getItem('user_info');
  if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };
  try {
    return JSON.parse(userInfo).id;
  } catch {
    throw { msg: '用户信息解析失败' };
  }
};

const RiskList = () => {
  const [assets, setAssets] = useState([]);
  const [riskScores, setRiskScores] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailData, setDetailData] = useState(null);

  // 拉取用户资产 & 风控评分
  const fetchData = async () => {
    try {
      setLoading(true);
      const assetRes = await $getUserAssets();
      const list = assetRes.data || [];
      setAssets(list);
      const userid = getUserId();
      // 带 Authorization Header 调用风控接口
      const scoreRes = await axios.get('/api/risk/scores', {
        params: { userid },
        headers: {
          Authorization: `Bearer ${localStorage.getItem('jwt_token')}`
        }
      });
      console.log("soceRes.data:",scoreRes.data);
      if (scoreRes.data.code === 0) {
        setRiskScores(scoreRes.data.data);
      } else {
        throw { msg: scoreRes.data.msg || '加载风险评分失败' };
      }
    } catch (err) {
      message.error(err.msg || 'js加载风险数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 查看详情
  const showDetail = async (id) => {
    try {
      setLoading(true);
      const detailRes = await axios.get(`/api/risk/asset/${id}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('jwt_token')}`
        }
      });
      if (detailRes.data.code === 0) {
        setDetailData(detailRes.data.data);
        setDetailVisible(true);
      } else {
        throw { msg: detailRes.data.msg || '获取详情失败' };
      }
    } catch (err) {
      message.error(err.msg || '获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 合并风险评分
  const dataSource = assets.map(a => {
    const found = riskScores.find(r => r.id === a.id);
    return {
      ...a,
      risk_score: found ? found.risk_score : null
    };
  });

  const columns = [
    { title: '资产ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '产品代码', dataIndex: 'products_id', key: 'products_id', width: 120 },
    { title: '产品名称', dataIndex: 'products_name', key: 'products_name', width: 150 },
    { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
    { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 100 },
    { title: '买入价', dataIndex: 'buy_price', key: 'buy_price', width: 100, render: v => `¥${v.toFixed(2)}` },
    {
      title: '风险评分', dataIndex: 'risk_score', key: 'risk_score', width: 120,
      render: v => v != null
        ? <Badge status={v >= 0.7 ? 'error' : v >= 0.3 ? 'warning' : 'success'} text={v.toFixed(4)} />
        : '-'
    },
    {
      title: '操作', key: 'action', width: 100,
      render: (_, record) => (
        <Button type="link" icon={<InfoCircleOutlined />} onClick={() => showDetail(record.id)}>
          详情
        </Button>
      )
    }
  ];

  return (
    <div className="risk-list-page">
      <div className="page-header">
        <h1>风险评估</h1>
        <Button icon={<ReloadOutlined />} onClick={fetchData}>刷新</Button>
      </div>
      <Card className="risk-card" bordered={false}>
        {loading ? (
          <div className="loading-container">
            <Spin size="large" tip="加载中..." />
          </div>
        ) : (
          <div className="table-container">
            <Table
              rowKey="id"
              dataSource={dataSource}
              columns={columns}
              pagination={{ pageSize: 10, showTotal: (total) => `共 ${total} 条` }}
              scroll={{ x: 'max-content', y: 500 }}
              rowClassName={(record) => {
                if (record.risk_score >= 0.7) return 'high-risk-row';
                if (record.risk_score <= 0.3) return 'low-risk-row';
                return 'medium-risk-row';
              }}
            />
          </div>
        )}
      </Card>

      <Modal
        title="资产风险详情"
        visible={detailVisible}
        footer={null}
        onCancel={() => setDetailVisible(false)}
        className="risk-modal"
      >
        {detailData && (
          <div className="detail-content">
            <p><Text strong>资产ID：</Text> {detailData.id}</p>
            <p><Text strong>产品：</Text> {detailData.products_id} - {detailData.products_name}</p>
            <p><Text strong>风险评分：</Text> {detailData.risk_score}</p>
            <div className="factors">
              <Text strong>因子拆解：</Text>
              <ul>
                {Object.entries(detailData.factors).map(([k, v]) => (
                  <li key={k}>{k}: {v}</li>
                ))}
              </ul>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default RiskList;
